export class EventEmitter {
  manyCbs: Record<any, any>

  constructor() {
    this.manyCbs = {}
    this.on = this.on.bind(this)
    this.trigger = this.trigger.bind(this)
    this.off = this.off.bind(this)
  }

  on(messageType: string | number, fn: Function) {
    const cbs = this.manyCbs[messageType]
    if (!cbs) {
      this.manyCbs[messageType] = [fn]
    } else {
      for (let i = 0; i < cbs.length; i++) {
        if (cbs[i].fn === fn) return
      }
      this.manyCbs[messageType].push(fn)
    }
  }

  trigger(messageType: string | number, ...json: any[]) {
    const cbs = this.manyCbs[messageType]
    if (!cbs || cbs.length === 0) {
      return
    }
    for (let i = 0; i < cbs.length; i++) {
      cbs[i](...json)
    }
  }

  off(messageType: string | number, fn?: Function) {
    if (messageType == null) {
      this.manyCbs = {}
    } else if (!fn) {
      this.manyCbs[messageType] = null
    } else {
      const cbs = this.manyCbs[messageType]
      if (!cbs) return
      for (let i = cbs.length - 1; i >= 0; i--) {
        if (cbs[i] === fn) {
          cbs.splice(i, 1)
          return
        }
      }
    }
  }
}
